package es.uclm.itsue.libraryreader;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class ItsueLibraryReaderActivity extends Activity {

	//public static final String SERVERIP = "161.67.0.82";
	public static final int SERVERPORT = 8080;
	
    private Button getBooksBT;
    private Button getFreeBooksBT;
    
    private TextView resultsCountTV;
    
    private EditText serverIP;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    	setContentView(R.layout.client);

    	getBooksBT = (Button) findViewById(R.id.all_books_BT);
    	getBooksBT.setOnClickListener(getBooksListener);

    	getFreeBooksBT = (Button) findViewById(R.id.free_books_BT);
    	getFreeBooksBT.setOnClickListener(getFreeBooksListener);
    	
    	resultsCountTV = (TextView) findViewById(R.id.results_count);
    	
    	serverIP = (EditText) findViewById(R.id.serverIP_TextView);
    }

    protected void onDestroy() {
    	super.onDestroy();
    }

    
    private OnClickListener getBooksListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
        	Log.i("Client", "Getting a list of books...");

        	// Use an AsyncTask to avoid blocking the UI thread
        	new AsyncTask<Void, Void, String>() {

        		@Override
        		protected String doInBackground(Void... arg0) {
        		    return serverDialog("{ command:'getBooks' , option:'all' }");
        		}

        		@Override
        		protected void onPostExecute(String inTxt) {
        		    try
        		    {
        		    	JSONArray books = new JSONArray(inTxt);
        		    	String x = "Encontrados " + books.length() + " libros:\n";

        		    	resultsCountTV.setText(x);
        		    	
        		    	List<String> items = new ArrayList<String>();
        		    	
        		    	for (int i=0; i<books.length(); i++)
        		    	{
        		    		JSONObject book= books.getJSONObject(i);
        		    		x += "------------\n";
        		    		x += book.getString("title") + "\n";
        		    		items.add(book.getString("title"));
        		    	}
        		    	Log.i("Client",x);
        		    	
        		    	ArrayAdapter<String> adapter = new ArrayAdapter<String>
        		    			(getBaseContext(), R.layout.list_item, items);        		    	
        		    	((ListView)findViewById(R.id.books_list)).setAdapter(adapter);        		    
        		    }
        		    catch (Exception ex)
        		    {
        		    	Log.e("Client","JSON Error: " + ex.getMessage());
        		    }        			
        		}
        	}.execute();				
        }
    };
    
    
    
    
    
    
    private OnClickListener getFreeBooksListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
			Log.i("Client", "Getting a list of free books...");

        	// Use an AsyncTask to avoid blocking the UI thread
        	new AsyncTask<Void, Void, String>() {

        		@Override
        		protected String doInBackground(Void... arg0) {
        		    return serverDialog("{ command:'getBooks' , option:'available' }");
        		}

        		@Override
        		protected void onPostExecute(String inTxt) {
        		    try
        		    {
        		    	JSONArray books = new JSONArray(inTxt);
        		    	String x = "Encontrados " + books.length() + " libros disponibles:\n";
        		    	
        		    	resultsCountTV.setText(x);        		    	
        		    	
        		    	List<String> items = new ArrayList<String>();        		    	

        		    	for (int i=0; i<books.length(); i++)
        		    	{
        		    		JSONObject book= books.getJSONObject(i);
        		    		x += "------------\n";
        		    		x += book.getString("title") + "\n";
        		    		items.add(book.getString("title"));        		    		
        		    	}
        		    	Log.i("Client",x);
        		    	
        		    	ArrayAdapter<String> adapter = new ArrayAdapter<String>
		    			(getBaseContext(), R.layout.list_item, items);
        		    	((ListView)findViewById(R.id.books_list)).setAdapter(adapter);        		    	
        		    }
        		    catch (Exception ex)
        		    {
        		    	Log.e("Client","JSON Error: " + ex.getMessage());
        		    }
        			
        		}
        	}.execute();
				
        
        }
    };

    
    
    private String serverDialog(String outTxt)
    {
		String inTxt = "";
		try {
			String SERVERIP = serverIP.getText().toString();
			Log.i("Client", "Conectting to "+ SERVERIP + ":" + SERVERPORT);
			InetAddress serverAddr = InetAddress.getByName(SERVERIP);
    		Socket clientSocket = new Socket(serverAddr, SERVERPORT);
			
			if(clientSocket.isConnected()) {
				
				PrintWriter out = new PrintWriter(
					new BufferedWriter(new OutputStreamWriter(clientSocket
						.getOutputStream())), true);

				out.println(outTxt);

				BufferedReader in = new BufferedReader(
						new InputStreamReader(clientSocket.getInputStream()),1024);

				        				
				Log.i("Client", "Response from server:\n");
				String line;
				while ((line = in.readLine()) != null) {
					Log.i("Client", line);
					inTxt += line;
				}
				Log.i("Client", "-----------------\n");
			}
			clientSocket.close();
		}
		catch (Exception e) {
			Log.e("Client", "Error connecting to the library server.", e);
		}
		return inTxt;
	}

    
}








